// Copyright Recursoft LLC 2019-2022. All Rights Reserved.

#include "SMGraphK2.h"
#include "Nodes/RootNodes/SMGraphK2Node_RootNode.h"
#include "Utilities/SMBlueprintEditorUtils.h"

USMGraphK2::USMGraphK2(const FObjectInitializer& ObjectInitializer)
	: Super(ObjectInitializer)
{
}

bool USMGraphK2::HasAnyLogicConnections() const
{
	if (bHasLogicConnectionsCached.IsSet())
	{
		return bHasLogicConnectionsCached.GetValue();
	}
	
	TArray<USMGraphK2Node_RuntimeNode_Base*> RootNodeList;

	// We want to find the node even if it's buried in a nested graph.
	FSMBlueprintEditorUtils::GetAllNodesOfClassNested<USMGraphK2Node_RuntimeNode_Base>(this, RootNodeList);
	for (const USMGraphK2Node_RuntimeNode_Base* RootNode : RootNodeList)
	{
		if (RootNode->IsConsideredForEntryConnection() && RootNode->GetOutputNode())
		{
			bHasLogicConnectionsCached = true;
			return true;
		}
	}

	bHasLogicConnectionsCached = false;
	return false;
}

void USMGraphK2::ResetCachedValues()
{
	bHasLogicConnectionsCached.Reset();

	TArray<USMGraphK2Node_RuntimeNode_Base*> RootNodeList;
	FSMBlueprintEditorUtils::GetAllNodesOfClassNested<USMGraphK2Node_RuntimeNode_Base>(this, RootNodeList);
	
	for (USMGraphK2Node_RuntimeNode_Base* RootNode : RootNodeList)
	{
		RootNode->ResetCachedValues();
	}
}

void USMGraphK2::PostRename(UObject* OldOuter, const FName OldName)
{
	Super::PostRename(OldOuter, OldName);
}

void USMGraphK2::NotifyGraphChanged()
{
	Super::NotifyGraphChanged();
	
	if (UBlueprint* Blueprint = FSMBlueprintEditorUtils::FindBlueprintForGraph(this))
	{
		if (!Blueprint->bBeingCompiled && !Blueprint->HasAnyFlags(RF_NeedLoad | RF_NeedPostLoad))
		{
			FSMBlueprintEditorUtils::FixUpAutoGeneratedFunctions(Blueprint, true);
		}
	}
}

void USMGraphK2::NotifyGraphChanged(const FEdGraphEditAction& Action)
{
	Super::NotifyGraphChanged(Action);
}
